<template>
  <!-- 货运单查询 -->
  <div>
    <TopFilter ref="topform" :list="topFilterList" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>
    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTables
        ref="table"
        columnsRef="shipmentOrderQuery"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :onRowSelectChange="selectChangeHandle"
        :onColumnsChange="(columns) => (this.columns = columns)"
      >
        <template slot="controls">
          <!-- <multiuse-button size="small" type="primary" @click="sapHandle()">交货单下发</multiuse-button> -->
          <multiuse-button size="small" type="primary" @click="addHandle(1)" :disabled="isDisable">同步店端物流信息</multiuse-button>
          <multiuse-button size="small" type="primary" @click="addHandle(2)">更新物流信息</multiuse-button>
          <multiuse-button size="small" type="primary" @click="addHandle(3)" :disabled="isDisable">发 运</multiuse-button>
          <multiuse-button size="small" type="primary" @click="addHandle(4)">导 出</multiuse-button>
        </template>
      </FilterTables>
    </Spin>

    <Drawer :visible.sync="detailVisible" :title="'货运单信息'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="80%">
      <detailModel :rowData="formData" @close="detailcloseHandler" />
    </Drawer>
    <BaseDialog :visible.sync="importVisible" :title="'更新物流信息'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <importFiles @close="importcloseHandler" />
    </BaseDialog>
    <BaseDialog :visible.sync="logisticsVisible" :title="'查询物流'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" >
      <logisticsModel :rowData="formData" @close="logisticscloseHandler" />
    </BaseDialog>

  </div>
</template>
<script>
import { getLevelOneArea } from '@/api/cms-common/dealerdata/index';
import { region } from '@/api/cms-common/region';
import { dictionary } from '@/utils/dictMixin';
import { queryList, shippedOrder, synchronousCarrier, exportList, exporturl, querySapDelivery } from '@/api/omSaleP/OrderManagement/ShipmentOrderQuery/index.js';
import detailModel from './detailModel';
import logisticsModel from './logisticsModel.vue'
import importFiles from './importFiles';
import { exportExcelFile } from '@/utils';
import moment from 'moment';
export default {
  name: 'shipmentOrderQuery',
  data() {
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchParams: {
        isDealer: 10041002,
      },
      tableList: [],
      fetchApi: queryList,
      formData: {},
      isDisable: true,
      selectList: [],
      exportLoading: false,
      importVisible: false,
      detailVisible: false,
      logisticsVisible: false
    };
  },
  mixins: [dictionary, region],
  components: {
    detailModel,
    importFiles,
    logisticsModel
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    //初始化所属区域数据
    this.getTopLevelArea();
    //初始化省份数据
    this.initProvince();
  },
  created() {},
  methods: {
    async sapHandle() {
      let res = await querySapDelivery();
    },
    // 所属区域
    async getTopLevelArea() {
      const res = await getLevelOneArea(15061015);
      if (res.resultCode === 200) {
        this.topFilterList.find((item) => item.fieldName === 'areaId').itemList = res.data.map((x) => ({ value: parseInt(x.id), text: x.orgName }));
      }
    },
    //初始化所在省份
    async initProvince() {
      let pl = await this.createRegionList();
      this.topFilterList.find((item) => item.fieldName === 'provinceId').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId) {
      this.topFilterList.find((item) => item.fieldName == 'cityId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName == 'cityId').itemList = [];
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      //初始化市，清除原值
      let city = this.topFilterList.find((item) => item.fieldName === 'cityId');
      city.itemList = cl;
      city.initialValue = '';
    },
    async addHandle(type) {
      if (type == 1) {
        //同步店端物流信息
        // console.log('选中数据', this.selectList);
        if (this.isDisable == false) {
          let arr = [];
          for (let i in this.selectList) {
            if (this.selectList[i].transStatus !== 21351002) {
              arr.push(this.selectList[i].doNo);
            }
          }
          if (arr.length > 0) {
            this.$notify({
              title: '警告',
              message: '以下数据无法进行{' + arr + '}店端物流信息同步操作,货运单货运状态非已发运',
              type: 'warning',
            });
            return;
          }
          await this.$confirm('是否同步选中订单物流信息?', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(async () => {
              this.isDisable = true;
              let res = await synchronousCarrier(this.selectList);
              if (res.resultCode === 200) {
                let total = res.data.total;
                let errorTotal = res.data.errorTotal;
                let error = res.data.error;
                this.$notify({
                  title: '店端物流信息同步状态',
                  message: '物流信息同步状态,同步' + total + '条,失败' + errorTotal + '条,失败列表' + error,
                  type: 'success',
                });
                // this.$notify({
                //   title: '成功',
                //   message: '发运成功',
                //   type: 'success',
                // });
                this.isDisable = false;
                this.fetchParams = Object.assign({}, this.fetchParams);
              }
            })
            .catch(() => {});
        }
      } else if (type == 2) {
        //更新物流信息
        this.importVisible = true;
      } else if (type == 3) {
        //发运
        // console.log('选中数据', this.selectList);
        if (this.isDisable == false) {
          let arr = [];
          for (let i in this.selectList) {
            if (this.selectList[i].transStatus !== 21351001) {
              arr.push(this.selectList[i].doNo);
            }
          }
          if (arr.length > 0) {
            this.$notify({
              title: '警告',
              message: '以下数据不能进行{' + arr + '}发运操作,货运单货运状态非待发运',
              type: 'warning',
            });
            return;
          }
          await this.$confirm('是否发运选中订单?', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(async () => {
              this.isDisable = true;
              let res = await shippedOrder(this.selectList);
              if (res.resultCode === 200) {
                let total = res.data.total;
                let errorTotal = res.data.errorTotal;
                let error = res.data.error;
                this.$notify({
                  title: '发运状态',
                  message: '发运状态,发运' + total + '条,失败' + errorTotal + '条,失败列表' + error,
                  type: 'success',
                });
                // this.$notify({
                //   title: '成功',
                //   message: '发运成功',
                //   type: 'success',
                // });
                this.isDisable = false;
                this.fetchParams = Object.assign({}, this.fetchParams);
              }
            })
            .catch(() => {});
        }
      } else {
        // let json = Object.assign({}, { CODE: 'CODE_0000034' }, this.fetchParams);
        // let res = await exporturl(json);
        // if (res.resultCode == 200) {
        //   this.$router.push('/admin/auth/oem/downloadCenter');
        // }

        this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
          confirmButtonText: '下载',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.$refs.topform.SUBMIT_FORM();
            let json = this.fetchParams;
            // this.exportLoading = true;
            exportList(json)
              .then((response) => {
                exportExcelFile(response.data, '货运单查询');
                // this.exportLoading = false;
              })
              .catch((err) => {
                // console.log(err);
              });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            });
          });
      }
    },
    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    //选中行数据
    selectChangeHandle(row) {
      if (row.length > 0) {
        this.isDisable = false;
        this.selectList = row || [];
      } else {
        this.isDisable = true;
        this.selectList = [];
      }
    },
    editHandle(data,type = 1) {
      this.formData = data;
      if(type === 1){
        this.detailVisible = true;
      } else {
        this.logisticsVisible = true;
      }

    },
    detailcloseHandler() {
      this.detailVisible = false;
    },
    logisticscloseHandler() {
      this.logisticsVisible = false
    },
    importcloseHandler() {
      this.importVisible = false;
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    createdFrom() {
      return [
        {
          type: 'TEXT_AREA',
          label: '结算订单编号',
          fieldName: 'doNo',
          maxlength: '10000',
          placeholder: '输入多个结算订单编号时，请用英文逗号或者换行隔开（例如：单号1,单号2……）',
          maxRows: 2,
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '查询多个请使用‘,’分隔',
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
        },
        {
          type: 'TEXT_AREA',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '输入多个VIN时，请用英文逗号或者换行隔开（例如：VIN1,VIN2……）',
          maxlength: '',
          maxRows: 2,
        },
        {
          type: 'INPUT',
          label: '货运单号',
          fieldName: 'transNo',
          placeholder: '请输入',
        },
        {
          type: 'SELECT',
          label: '发运状态',
          fieldName: 'transStatus',
          placeholder: '请选择',
          itemList: this.createDictList('2135'),
        },
        {
          type: 'SELECT',
          label: '所属区域',
          fieldName: 'areaId',
          placeholder: '请选择',
          itemList: [],
        },
        {
          type: 'SELECT',
          label: '省份',
          fieldName: 'provinceId',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          change: (props) => this.initCity(props),
        },
        {
          type: 'SELECT',
          label: '城市',
          fieldName: 'cityId',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
        },
        {
          type: 'INPUT',
          label: 'SAP销售单号',
          fieldName: 'sapNo',
          placeholder: '请输入',
        },
        {
          type: 'SELECT',
          label: '运输方式',
          fieldName: 'transportType',
          placeholder: '请选择',
          itemList: this.createDictList('2409'),
        },
        {
          type: 'SELECT',
          label: '车牌号',
          fieldName: 'isTrailerBrand',
          placeholder: '请选择',
          itemList: [
            { value: 1, text: '有' },
            { value: 0, text: '无' },
          ],
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 150,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 1)}>
                  详情
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 2)} disabled={props.row.transportType == 24091002 ? true : false}>
                  查看物流
                </multiuse-button>
              </div>
            );
          },
        },
        {
          title: '所属区域',
          dataIndex: 'areaName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '省份',
          dataIndex: 'provinceName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '城市',
          dataIndex: 'cityName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '货运单号',
          dataIndex: 'transNo',
          sorter: true,
          filter: true,
          width: 200,
          filterType: 'input',
        },
        {
          title: '发运状态',
          dataIndex: 'transStatus',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return <span>{this.createDictText(p.row.transStatus, '2135')}</span>;
          },
        },
        {
          title: 'SAP销售单号',
          dataIndex: 'sapNo',
          sorter: true,
          filter: true,
          width: 200,
          filterType: 'input',
        },
        {
          title: 'DMS批售订单编号',
          dataIndex: 'orderNo',
          sorter: true,
          filter: true,
          width: 200,
          filterType: 'input',
        },
        {
          title: '结算订单编号',
          dataIndex: 'doNo',
          sorter: true,
          filter: true,
          width: 200,
          filterType: 'input',
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          sorter: true,
          filter: true,
          width: 200,
          filterType: 'input',
        },
        {
          title: '资金类型',
          dataIndex: 'accountTypeName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '合格证邮寄地址',
          dataIndex: 'certificateMailAddress',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '合格证发放方式',
          dataIndex: 'certificateIssueType',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return <span>{this.createDictText(p.row.certificateIssueType, '2138')}</span>;
          },
        },
        {
          title: '收车地址',
          dataIndex: 'address',
          sorter: true,
          filter: true,
          width: 200,
          filterType: 'input',
        },
        {
          title: '送达城市',
          dataIndex: 'orderCity',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '联系人',
          dataIndex: 'linkMan',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '联系电话',
          dataIndex: 'linkPhone',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '承运单号',
          dataIndex: 'carrierBillCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '承运/自提单位',
          dataIndex: 'carrierName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '承运人/自提人',
          dataIndex: 'carrierPersonName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '预计提车时间',
          dataIndex: 'estimatedPickupDate',
          sorter: true,
          filter: true,
          width: 150,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd',
        },
        {
          title: '承运/自提时间',
          dataIndex: 'deliveryDate',
          sorter: true,
          filter: true,
          width: 150,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd',
        },
        {
          title: '发车人',
          dataIndex: 'sendPersonName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车牌号',
          dataIndex: 'trailerBrand',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '承运司机',
          dataIndex: 'driverName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '司机联系方式',
          dataIndex: 'driverTel',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '当前位置',
          dataIndex: 'eventLocation',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '收车人',
          dataIndex: 'receiver',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '收车时间',
          dataIndex: 'receiveDate',
          sorter: true,
          filter: true,
          width: 150,
          filterType: 'input',
        },
        {
          title: '运输方式',
          dataIndex: 'transportType',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return <span>{this.createDictText(p.row.transportType, '2409')}</span>;
          },
        },
        {
          title: '物料编码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          width: 200,
          filterType: 'input',
        },
        {
          title: '物料描述',
          dataIndex: 'productName',
          sorter: true,
          filter: true,
          width: 400,
          filterType: 'input',
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '配置',
          dataIndex: 'configName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '选装',
          dataIndex: 'optionName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '内饰',
          dataIndex: 'trimName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
      ];
    },
  },
};
</script>
<style scoped lang="scss">
.title {
  padding: 10px 0;
  font-size: 16px;
}
</style>
